package com.py.framework.core.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件处理工具类
 * 
 * @author Leegern
 * @date 2018年3月6日
 */
public class FileUtils {

	/** 字符集：UTF-8 **/
	public static final String CHARSET_UTF8 = "UTF-8";

	/** 文件后缀名：word **/
	public static final String SUFFIX_WORD = ".docx";

	/** 文件后缀名：excel **/
	public static final String SUFFIX_EXCEL = ".xlsx";

	/** 文件分隔符 **/
	public static final String FILE_SEPARATOR = "/";

	/**
	 * 获取web应用根目录路径
	 * 
	 * @return
	 */
	public static String getWebRootPath() {
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		if (null == classLoader) {
			classLoader = ClassLoader.getSystemClassLoader();
		}
		java.net.URL url = classLoader.getResource("");
		String rootClassPath = url.getPath() + FILE_SEPARATOR;
		File rootFile = new File(rootClassPath);
		String webInfoPath = rootFile.getParent() + FILE_SEPARATOR;
		File webInfoDir = new File(webInfoPath);
		String webRootPath = webInfoDir.getParent() + FILE_SEPARATOR;
		return webRootPath;
	}

	/**
	 * 流输出
	 * 
	 * @param is
	 *            输入流
	 * @param os
	 *            输出流
	 * @throws IOException
	 */
	public static void pushStream(InputStream is, OutputStream os) throws IOException {
		byte[] bytes = new byte[1024];
		int len = 0;
		try {
			while ((len = is.read(bytes)) > 0) {
				os.write(bytes, 0, len);
			}
			os.flush();
		} finally {
			if (null != is)
				is.close();
			if (null != os)
				os.close();
		}
	}

	public static List<String> readFile(String fileName) {
		List<String> list = new ArrayList<String>();
		BufferedReader reader = null;
		FileInputStream fis = null;
		try {
			File f = new File(fileName);
			if (f.isFile() && f.exists()) {
				fis = new FileInputStream(f);
				reader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
				String line;
				while ((line = reader.readLine()) != null) {
					if (!"".equals(line)) {
						list.add(line);
					}
				}
			}
		} catch (Exception e) {

		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {

			}
			try {
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {

			}
		}
		return list;
	}

	public static byte[] toByteArray(InputStream in) throws IOException {

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024 * 4];
		int n = 0;
		while ((n = in.read(buffer)) != -1) {
			out.write(buffer, 0, n);
		}
		return out.toByteArray();
	}
}